import { Request, Response } from 'express'
import { User } from '../models/User'
import { generateToken } from '../utils/jwt'
import { RegisterData, LoginData, AuthRequest } from '../types'

export const register = async (req: Request, res: Response): Promise<void> => {
  try {
    const { username, email, password }: RegisterData = req.body

    // 检查用户是否已存在
    const existingUser = await User.findOne({
      $or: [{ email }, { username }]
    })

    if (existingUser) {
      res.status(400).json({
        success: false,
        message: '用户名或邮箱已存在'
      })
      return
    }

    // 创建新用户
    const user = new User({ username, email, password })
    await user.save()

    // 生成token
    const token = generateToken({ id: user._id })

    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        token,
        user: {
          id: user._id,
          username: user.username,
          email: user.email
        }
      }
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '注册失败',
      error: (error as Error).message
    })
  }
}

export const login = async (req: Request, res: Response): Promise<void> => {
  try {
    const { email, password }: LoginData = req.body

    // 查找用户
    const user = await User.findOne({ email })
    if (!user) {
      res.status(401).json({
        success: false,
        message: '邮箱或密码错误'
      })
      return
    }

    // 验证密码
    const isPasswordValid = await (user as any).comparePassword(password)
    if (!isPasswordValid) {
      res.status(401).json({
        success: false,
        message: '邮箱或密码错误'
      })
      return
    }

    // 生成token
    const token = generateToken({ id: user._id })

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user._id,
          username: user.username,
          email: user.email
        }
      }
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '登录失败',
      error: (error as Error).message
    })
  }
}

export const getProfile = async (req: AuthRequest, res: Response): Promise<void> => {
  try {
    const user = await User.findById(req.user?.id)
    
    if (!user) {
      res.status(404).json({
        success: false,
        message: '用户不存在'
      })
      return
    }

    res.json({
      success: true,
      data: {
        user: {
          id: user._id,
          username: user.username,
          email: user.email,
          createdAt: user.createdAt
        }
      }
    })
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户信息失败',
      error: (error as Error).message
    })
  }
}